package com.ics.web.controller.travelstar.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ics.framework.util.PageUtil;
import com.ics.web.controller.travelstar.domain.TbAllTiresLine;
import com.ics.web.controller.travelstar.dto.AllTiresLineDTO;
import com.ics.web.controller.travelstar.mapper.AllTiresLineMapper;
import com.ics.web.controller.travelstar.service.AllTiresLineService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author shaoly
 * @description
 * @ClassName AllTiresLineServiceImpl.java
 * @createTime 2024年12月13日 17:16:43
 */
@Service
@Slf4j
public class AllTiresLineServiceImpl extends ServiceImpl<AllTiresLineMapper, TbAllTiresLine>
    implements AllTiresLineService {


    @Override
    public IPage<TbAllTiresLine> listPage(AllTiresLineDTO lineDTO) {
        LambdaQueryWrapper<TbAllTiresLine> wrapper = Wrappers.lambdaQuery();
        if (lineDTO.getPId() != null) {
            wrapper.eq(TbAllTiresLine::getPId, lineDTO.getPId());
        }
        if (StringUtils.isNotBlank(lineDTO.getName())) {
            wrapper.like(TbAllTiresLine::getName, lineDTO.getName());
        }
        wrapper.orderByAsc(TbAllTiresLine::getPId, TbAllTiresLine::getTOrder);
        return this.baseMapper.selectPage(PageUtil.getPage(lineDTO), wrapper);
    }

    @Override
    public List<TbAllTiresLine> treeList() {
        List<TbAllTiresLine> list = this.lambdaQuery()
                .orderByAsc(TbAllTiresLine::getPId, TbAllTiresLine::getTOrder)
                .list();
        Map<Long, TbAllTiresLine> data = new HashMap<>();
        for (TbAllTiresLine tiresLine : list) {
            data.put(tiresLine.getId(), tiresLine);
        }
        Iterator<TbAllTiresLine> iterator = list.iterator();
        while (iterator.hasNext()) {
            TbAllTiresLine line = iterator.next();
            if (-1 == line.getPId()) {
                continue;
            }
            TbAllTiresLine tbAllTiresLine = data.get(line.getPId());
            if (tbAllTiresLine != null) {
                tbAllTiresLine.getChildren().add(line);
            }
            iterator.remove();
        }

        return list;
    }

    @Override
    public List<TbAllTiresLine> getParentList() {
        return  this.lambdaQuery()
                .eq(TbAllTiresLine::getPId, -1)
                .orderByAsc(TbAllTiresLine::getPId, TbAllTiresLine::getTOrder)
                .list();
    }


}
